package com.ruoyi.security.config;


import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.ruoyi.security.common.R;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Spring security 登录成功后返回一串json
 */
@Component("MyAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String  currentUser = authentication.getName();
        System.out.println("成功后");
//        System.out.println(currentUser.getClass());
//        User principal =(User) authentication.getPrincipal();
//        Object username = principal.getUsername();
//        System.out.println("username"+username.toString());
//        System.out.println("usernameClass"+username.getClass());

//        System.out.println("principal"+principal);

        //获取用户名 和id
        String name ="userName\":\"";
        String id ="userId\":";

        int beginId = currentUser.indexOf(id);
        String userId = currentUser.substring(beginId + id.length(), currentUser.indexOf(",", beginId));


        int beginName = currentUser.indexOf(name);
        String userName = currentUser.substring(beginName + name.length(), currentUser.indexOf("\"}", beginName));

        logger.info("用户"+currentUser+"登录成功");
        System.out.println("登录用户id："+userId);
        System.out.println("登录用户名："+userName);

        //自己编码的JWTtoken
        //生成令牌
        String token = JWT.create()
            .withClaim("userid",userId) //payload
            .withClaim("username",userName)
            .sign(Algorithm.HMAC256("ILoveYuzuruHannu")); //签名/密钥


        String url = "http://localhost/login";
        System.out.println(doGet(url, token));
        System.out.println("已发送");
        //response.setContentType("application/json;charset=UTF-8");
        //response.getWriter().append(JSON.toJSON(R.ok(token,"操作成功")).toString());
//        response.getWriter().append("{\"code\":0,\"msg\":\"登录成功!\",\"data\":\"success\"}");
    }

    public static String doGet(String url, String token) {
        String reponse = null;
        // 1.拿到一个httpclient的对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2.设置请求方式和请求信息
        // 设置请求格式
        HttpGet httpGet = new HttpGet(url+"?code="+token);
//        httpGet.setHeader("Authorization", token);  //假设值测试是否可取得


        try {
            // 3.执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 4.获取返回值--在这测试是，不需要
            //   在这个功能的测试里，不重要
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity,"utf-8");
//            reponse = EntityUtils.toString(entity, Charset.forName("utf-8"));
//            System.out.println(reponse);
            // 5.打印
            return result;
        }
        catch (Exception e ) {
            e.printStackTrace();
        }

        return reponse;
    }
}
